package com.fzebu.fastboot.form.parser;

import com.fzebu.fastboot.form.bean.FieldBean;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;

import java.util.ArrayList;
import java.util.List;

/**
 *  1：单行文本框 2：多行文本框 3：浏览按钮 4：check框 5：选择框
 * @author Jack
 */
public class FieldDbTypeParser {

    @Setter
    private FieldBean fieldBean;
    private static final String INT = "int";
    private static final String DECIMAL = "decimal";
    private static final String TEXT = "text";
    private static final String BROWSER_TYPE = "3";
    private static final String SELECT_TYPE = "5";
    private static final String TEXT_TYPE = "1";

    public String doParse() {
        String type = StringUtils.substringBefore(fieldBean.getFieldDbType(), "(");
        // 	1：单行文本框 2：多行文本框 3：浏览按钮 4：check框 5：选择框
        if (INT.equals(type)) {
            fieldBean.setFieldType("Integer");
            handlerNumber();
        } else if (DECIMAL.equals(type)) {
            fieldBean.setFieldType("Double");
            handlerNumber();
        } else {
            fieldBean.setFieldType("String");
            if (TEXT.equals(type)) {
                fieldBean.setAnnotationText("\n\t@Text");
            }
            if (BROWSER_TYPE.equals(fieldBean.getFieldHtmlType())) {
                handlerBrowser();
            }
        }
        if (SELECT_TYPE.equals(fieldBean.getFieldHtmlType())) {
            handlerSelect();
        }
        String aliasText = "\n\t@Alias(value=\""+ fieldBean.getFieldName() +"\", desc=\""+ fieldBean.getFieldLabel() +"\")";
        String annotationText;
        if (fieldBean.getAnnotationText() != null) {
            annotationText = fieldBean.getAnnotationText() + aliasText;
        } else {
            annotationText = aliasText;
        }
        return annotationText;
    }

    private void handlerSelect() {
        RecordSet rs = new RecordSet();
        String sql = "select SELECTVALUE, SELECTNAME from workflow_selectitem where FIELDID=?";
        rs.executeQuery(sql, fieldBean.getId());
        List<String> selectItems = new ArrayList<>(rs.getCounts());
        while (rs.next()) {
            String selectValue = rs.getString("SELECTVALUE");
            String selectName = rs.getString("SELECTNAME");
            selectItems.add("\"" + selectValue + "-" + selectName + "\"");
        }
        String text = "\n\t@Select({"+ StringUtils.join(selectItems, ",") +"})";
        fieldBean.setAnnotationText(text);
    }

    private void handlerBrowser() {
        if (TEXT.equals(fieldBean.getFieldDbType())) {
            fieldBean.setAnnotationText("\n\t@Browser(multiple=true)");
        } else {
            fieldBean.setAnnotationText("\n\t@Browser");
        }
    }

    private void handlerNumber() {
        if (TEXT_TYPE.equals(fieldBean.getFieldHtmlType())) {
            fieldBean.setAnnotationText("\n\t@Number");
        }
    }
}
